<template>
  <div class="kmTable">
    <el-button class="add" type="primary" size="mini" @click="addKnowledge"
      v-if="importType === 'knowledge_mgt_channel' || limitArr.indexOf(limitObj.add) > -1">
      {{`添加${importType === 'knowledge_mgt_channel' ? '知识点' : '常用语'}`}}</el-button>
    <commonTable
      :key="currentId"
      v-loading="showLoading"
      :headers="tableHeaders"
      :data="tableData"
      :pagingData="pageData"
      :headersConfig="false"
      :selection="checkHasAccess.canEdit"
      :batchs="configBatchs"
      ref="tableRef"
      @batchClick="batchClick"
      @pageChange="pageChange"
      @pageSizeChange="pageSizeChange">
      <template slot="column">
        <template v-for="(item, index) in tableHeaders">
          <u-table-column
            v-if="
              item.prop !== 'oprate' &&
              item.prop !== 'statusName' &&
              item.prop !== 'title'
            "
            :resizable="false"
            :prop="item.prop"
            :label="item.label"
            :key="item.label + index"
            :sortable="item.sortable"
            :min-width="item.width > 0 ? item.width : ''"
            :show-overflow-tooltip="item.width > 0"
            align="left">
          </u-table-column>
          <u-table-column
            v-if="item.prop === 'title' && (checkHasAccess.canEdit || checkHasAccess.canShow)"
            :resizable="false"
            :prop="item.prop"
            :label="item.label"
            :key="item.label + index"
            :min-width="item.width > 0 ? item.width : ''"
            :show-overflow-tooltip="item.width > 0"
            align="left">
            <template slot-scope="scope">
              <span class="tableName" @click="lookFun(scope.row)">
                {{scope.row.title}}
              </span>
            </template>
          </u-table-column>
          <u-table-column
            v-if="item.prop === 'statusName'"
            :resizable="false"
            :prop="item.prop"
            :label="item.label"
            :key="item.label + index"
            :min-width="item.width > 0 ? item.width : ''"
            :show-overflow-tooltip="item.width > 0"
            align="left">
            <template slot-scope="scope">
              <i class="V7_iconV7tubiao_dian V7_iconfont" :style="scope.row.status | handleStatusIcon"></i>
              {{scope.row.statusName}}
            </template>
          </u-table-column>
          <u-table-column
            :label="item.label"
            v-if="item.prop === 'oprate'"
            :key="item.label + index"
            align="left"
            fixed="right"
            width="50">
            <template slot-scope="scope" v-if="checkHasAccess.canEdit">
              <span class="oprate-btn" v-if="importType === 'knowledge_mgt_channel' || limitArr.indexOf(limitObj.edit) > -1"
                @click="handleDetail(scope.row)">编辑</span>
              <span class="del-btn" v-if="importType === 'knowledge_mgt_channel' || limitArr.indexOf(limitObj.del) > -1"
                @click="handleDel(scope.row)">删除</span>
            </template>
          </u-table-column>
        </template>
      </template>
    </commonTable>
    <el-dialog
      custom-class="batchMove"
      title="批量移动至"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div v-if="importType === 'knowledge_mgt_channel'">
        <el-radio v-model="batchData.type" label="mv">移动到该目录</el-radio>
        <el-radio v-model="batchData.type" label="cp">复制到该目录</el-radio>
      </div>
      <p v-if="checkHasAccess.canEdit">目录名称</p>
      <el-cascader
        ref="cascader"
        v-model="batchData.catalogId"
        :props="{ checkStrictly: true, value: '_id' }"
        :options="batchData.catalogOpt"
        clearable
        filterable
      >
      </el-cascader>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchMoveCancelFun">取 消</el-button>
        <el-button type="primary" @click="batchMoveSaveFun">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import commonTable from '@/components/configCommon/table.vue'
import { KmModule } from '@/store/modules/km/index'
import { checkPermission } from '@/utils/directive'
import { knowledgeAccess } from '@/utils/kmAccess'
import _isEmpty from 'lodash/isEmpty'
@Component({
  name: 'kmTable',
  components: { commonTable },
  filters: {
    handleStatusIcon (item: string) {
      return item === 'valid' ? 'color: #2ED47A' : 'color: #FC6B5C'
    }
  }
})
export default class KmTable extends Vue {
  private $bus: any
  private $store: any
  private $route: any
  private $getCache: any
  private $confirm: any
  private $message: any
  private $router: any

  private exportVisible = false

  private limitArr = []

  private limitObj = {
    add: '',
    edit: '',
    del: ''
  }

  private dialogVisible: boolean = false

  private currentId: string = '' // 当前目录id

  private showLoading = false

  private searchForm = {}

  private tableHeaders: any = []

  private tableData = []

  private pageData: any = { total: 0, limit: 10, page: 1 }

  private configBatchs: any = []

  private lastImportType = ''

  private batchData = {
    type: 'mv',
    catalogId: '',
    catalogOpt: [],
    list: [],
    curCatalogId: ''
  }

  get importType () {
    return this.$route.path.split('/')[3]
  }

  private lookFun (obj: string) { // 查看知识点
    this.$emit('lookFun', obj)
  }

  get checkHasAccess () {
    return knowledgeAccess(this.$store.state.km.clickNode.node, this.$store.state.common.session)
  }

  private checkAccess (node: any) {
    return knowledgeAccess(node, this.$store.state.common.session)
  }

  public deepDisable (list) {
    const each = (arr) => {
      arr.forEach(i => {
        const { canEdit, canShow } = this.checkAccess(i)
        i.disabled = !canEdit && !canShow
        if (!_isEmpty(i.children)) {
          each(i.children)
        }
      })
    }
    each(list)
  }

  private batchClick (action: string, list: any) {
    this.batchData.list = list
    if (action === 'handleBatchsDel') {
      this.$confirm(`确定批量删除${this.importType === 'knowledge_mgt_channel' ? '知识点' : '常用语'}知识点吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleBatchsDel(list)
      }).catch(e => { console.log(e) })
    } else if (action === 'handleBatchsMove') { // 批量移动
      this.dialogVisible = true
      const kmData = { url: '/im-km/action/catalog/list', method: 'POST', data: { kmType: 'inner' } }
      const quickReplyData = {
        url: `/im-km/quick-reply/action/${this.importType === 'personal_language' ? 'agent' : 'common'}/category/list`,
        method: 'post',
        data: { isQuickQuery: false }
      }
      const actionData = this.importType === 'knowledge_mgt_channel' ? kmData : quickReplyData
      KmModule.KmCommonAction(actionData).then(res => {
        if (res && res.success) {
          const options = res.data.tree || []
          this.deepDisable(options)
          this.batchData.catalogOpt = options
        }
      })
    } else if (action === 'handleBatchsExport') {
      this.$confirm('确定批量导出常用语吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleBatchExport(list)
      }).catch(e => { console.log(e) })
    }
  }

  private handleBatchExport (list) { // 批量导出
    const isAll = !Array.isArray(list)
    let sendData = {
      type: this.importType === 'personal_language' ? 'agent' : 'common',
      ids: isAll ? [] : list,
      categoryId: this.currentId === 'all' ? '' : this.currentId,
      isAll
    }
    if (isAll) {
      sendData = Object.assign({ ...sendData, ...this.searchForm })
    }
    const actionData = {
      url: '/im-km/export/action/exportQuickReplyTask',
      method: 'post',
      data: sendData
    }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private jumpToTransmissionCenter () {
    this.$router.push(`/transmission_center/index/tx_export_task?taskModule=${this.importType === 'personal_language' ? 'agentqr' : 'commonqr'}`)
  }

  private handleBatchsDel (list: any) { // 批量删除
    const catalogId = this.$route.params.id || ''
    let data = {}
    const kmData = {
      url: '/im-km/action/item/delete',
      method: 'POST',
      data: { itemIds: Array.isArray(list) ? list : [], isAll: !Array.isArray(list), kmType: 'inner', catalogId }
    }
    const quickReplyData = {
      url: `/im-km/quick-reply/action/${this.importType === 'personal_language' ? 'agent' : 'common'}/content/delete`,
      method: 'POST',
      data: { ids: Array.isArray(list) ? list : [], isAll: !Array.isArray(list), categoryId: catalogId, ...this.searchForm }
    }
    data = this.importType === 'knowledge_mgt_channel' ? kmData : quickReplyData
    KmModule.KmCommonAction(data).then((res: any) => {
      if (res && res.success) {
        this.$message.success(`批量删除${this.importType === 'knowledge_mgt_channel' ? '知识点' : '常用语'}成功`)
        const tableRef: any = this.$refs.tableRef
        tableRef.cancelSelectFun()
        this.getTableList()
      }
    })
  }

  private batchMoveSaveFun () {
    if (!this.batchData.catalogId) {
      this.$message.error('请选择目录')
      return
    }
    const { type, catalogId, list, curCatalogId } = this.batchData
    const lastCatalogId = catalogId[catalogId.length - 1]
    const kmData = { // 知识库
      url: '/im-km/action/item/batchUpdate',
      method: 'POST',
      data: {
        kmType: 'inner',
        type,
        catalogId: lastCatalogId,
        itemIds: Array.isArray(list) ? list : [],
        isAll: !Array.isArray(list),
        curCatalogId
      }
    }
    const quickReplyData = { // 常用语
      url: `/im-km/quick-reply/action/${this.importType === 'personal_language' ? 'agent' : 'common'}/content/batchUpdate`,
      method: 'POST',
      data: {
        categoryId: curCatalogId,
        ids: Array.isArray(list) ? list : [],
        isAll: !Array.isArray(list),
        newCategoryId: lastCatalogId,
        ...this.searchForm
      }
    }
    const actionData = this.importType === 'knowledge_mgt_channel' ? kmData : quickReplyData
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('批量移动成功')
        this.batchData.catalogId = ''
        this.batchData.type = 'mv'
        this.batchData.curCatalogId = ''
        this.batchData.list = []
        this.dialogVisible = false
        const tableRef: any = this.$refs.tableRef
        tableRef.cancelSelectFun()
        this.getTableList()
      }
    })
  }

  private batchMoveCancelFun () {
    this.batchData.catalogId = ''
    this.batchData.curCatalogId = ''
    this.batchData.type = 'mv'
    this.batchData.list = []
    this.dialogVisible = false
  }

  private getTableList (searchForm?: any) { // 获取table数据
    if (searchForm) { // 新增回到第一页
      this.pageData.current = 1
    }
    const url = this.importType === 'knowledge_mgt_channel' ? '/im-km/action/item/list'
      : `/im-km/quick-reply/action/${this.importType === 'personal_language' ? 'agent' : 'common'}/content/list`
    const actionData = {
      url,
      method: 'POST',
      data: { page: this.pageData.page, limit: this.pageData.limit, ...searchForm }
    }
    if (this.importType === 'knowledge_mgt_channel') {
      actionData.data.type = 'km'
      actionData.data.kmType = 'inner'
      actionData.data.catalogId = this.currentId
    } else {
      if (this.currentId !== 'all') { // 查看全部类别不传categoryId
        actionData.data.categoryId = this.currentId
      }
    }
    if (searchForm) {
      let isEmpty = true
      if (
        searchForm.updateUser !== '' ||
        (searchForm.updateTime && searchForm.updateTime.length > 0) ||
        searchForm.keywordsType !== 'all' ||
        searchForm.createUser !== '' ||
        searchForm.status !== ''
      ) {
        isEmpty = false
      }
      if (!isEmpty) { // 当搜索条件不为空时 要去掉当前的目录id，搜全局
        delete actionData.data.catalogId
      }
    }
    this.showLoading = true
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const list = res.data.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.pageData.limit)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pageData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pageData.page = page
            this.getTableList()
            return false
          }
        }
        list.forEach(item => {
          item.statusName = item.status === 'valid' ? '有效' : '无效'
          const agentObj = this.$store.state.common.publicCache.userListObj[item.updateUser] // 座席
          item.agentName = agentObj ? agentObj.name : '--'
          const createObj = this.$store.state.common.publicCache.userListObj[item.createUser] // 创建人
          item.createName = createObj ? createObj.name : '--'
        })
        this.tableData = list
        this.pageData.total = res.data.count || 0
      }
      this.showLoading = false
    })
  }

  private pageChange (page: number) { // 翻页
    this.pageData.page = page
    this.getTableList()
  }

  private pageSizeChange (size: number) { // 改变每页显示条数
    this.pageData.limit = size
    this.getTableList()
  }

  private addKnowledge () { // 添加知识点
    this.$emit('addKnowledge')
  }

  private handleDetail (row: any) { // 编辑知识点详情
    if (this.importType === 'knowledge_mgt_channel') {
      const actionData = { url: '/im-km/action/item/show', method: 'POST', data: { itemId: row._id, kmType: 'inner' } }
      KmModule.KmCommonAction(actionData).then(res => {
        if (res && res.success) {
          this.$emit('handleDetail', res.data.row)
        }
      })
    } else {
      this.$emit('handleDetail', row)
    }
  }

  private handleDel (row: any) { // 知识点删除
    this.$confirm(`确定批量删除${this.importType === 'knowledge_mgt_channel' ? '知识点' : '常用语'}知识点吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const catalogId = this.$route.params.id || ''
      let data = {}
      const kmData = { url: '/im-km/action/item/delete', method: 'POST', data: { itemIds: [row._id], kmType: 'inner', catalogId, isAll: false } }
      const quickReplyData = {
        url: `/im-km/quick-reply/action/${this.importType === 'personal_language' ? 'agent' : 'common'}/content/delete`,
        method: 'POST',
        data: { ids: [row._id], isAll: false, categoryId: catalogId }
      }
      data = this.importType === 'knowledge_mgt_channel' ? kmData : quickReplyData
      KmModule.KmCommonAction(data).then((res: any) => {
        if (res && res.success) {
          this.$message.success(`删除${this.importType === 'knowledge_mgt_channel' ? '知识点' : '常用语'}成功`)
          this.getTableList()
        }
      })
    })
  }

  private initTableList () {
    if (Object.keys(this.searchForm).length === 0) {
      this.$getCache('/base/action/general/cache/query', ['userList'], true).then(res => {
        if (this.$route.params.id) {
          this.currentId = this.$route.params.id
          this.getTableList()
        }
      })
    } else {
      this.getTableList()
    }
  }

  private directoryClick (data) {
    this.currentId = (data && data.node._id) || 'all'
    this.batchData.curCatalogId = (data && data.node._id) || ''
    this.searchForm = {}
    this.initTableList()
  }

  private kmSearchFun (searchForm: any) {
    this.searchForm = searchForm
    this.getTableList(searchForm)
  }

  private activated () {
    if (this.importType === 'knowledge_mgt_channel') { // 知识库
      this.tableHeaders = [
        { label: '知识名称', prop: 'title', width: 110 },
        { label: '知识状态', prop: 'statusName', width: 80 },
        { label: '创建时间', prop: 'createTime', width: 120, sortable: true },
        { label: '创建人', prop: 'createName', width: 120 },
        { label: '最近更新时间', prop: 'updateTime', width: 120, sortable: true },
        { label: '最近更新人', prop: 'agentName', width: 100 },
        { label: '点击量', prop: 'hits', width: 100, sortable: true },
        { label: '操作', prop: 'oprate', disenable: true }
      ]
      this.configBatchs = [
        { name: '批量删除', action: 'handleBatchsDel' },
        { name: '批量移动', action: 'handleBatchsMove' }
      ]
    } else { // 常用语
      this.tableHeaders = [
        { label: '快捷词', prop: 'title', width: 80 },
        { label: '内容', prop: 'content', width: 110 },
        { label: '最近更新时间', prop: 'updateTime', width: 130, sortable: true },
        { label: '最近更新人', prop: 'agentName', width: 100 },
        { label: '点击量', prop: 'hits', width: 90, sortable: true },
        { label: '操作', prop: 'oprate', disenable: true }
      ]
      let handlers: any = []
      if (this.importType === 'personal_language') {
        this.tableHeaders.splice(3, 1) // 个人常用语去掉最近更新人
        if (checkPermission(null, { value: ['batch_delete_personal_language'] })) { // 批量删除
          handlers.push({ name: '批量删除', action: 'handleBatchsDel' })
        }
        if (checkPermission(null, { value: ['batch_move_personal_language'] })) { // 批量移动权限
          handlers = [...handlers,
            ...[
              { name: '批量移动', action: 'handleBatchsMove' }
            ]
          ]
        }
        if (checkPermission(null, { value: ['batch_export_personal_language'] })) { // 批量导出
          handlers = [...handlers,
            ...[
              { name: '批量导出', action: 'handleBatchsExport' }
            ]
          ]
        }
      } else {
        if (checkPermission(null, { value: ['batch_delete_common_language'] })) { // 批量删除
          handlers.push({ name: '批量删除', action: 'handleBatchsDel' })
        }
        if (checkPermission(null, { value: ['batch_move_common_language'] })) { // 批量移动权限
          handlers = [...handlers,
            ...[
              { name: '批量移动', action: 'handleBatchsMove' }
            ]
          ]
        }
        if (checkPermission(null, { value: ['batch_export_common_language'] })) { // 批量导出
          handlers = [...handlers,
            ...[
              { name: '批量导出', action: 'handleBatchsExport' }
            ]
          ]
        }
      }
      this.configBatchs = handlers
      // if (this.lastImportType === this.importType) {
      //   console.log('come')
      //   this.initTableList()
      // }
    }
  }

  private mounted () {
    this.searchForm = {}
    this.initTableList()
    this.limitArr = this.$store.state.common.session.user.functions // 权限处理
    switch (this.importType) {
      case 'personal_language':
        this.limitObj.add = 'add_personal_language'
        this.limitObj.edit = 'edit_personal_language'
        this.limitObj.del = 'delete_personal_language'
        break
      case 'common_language':
        this.limitObj.add = 'add_common_language'
        this.limitObj.edit = 'edit_common_language'
        this.limitObj.del = 'delete_common_language'
        break
    }
  }

  private deactivated () {
    this.lastImportType = this.importType
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
.add
  margin-top 15px
.kmTable
  height calc(100% - 20px)
  .tableName
    color #008CEE
    cursor pointer
  .oprate-btn
    color $c-main
    margin-right 10px
    cursor pointer
  .del-btn
    color #fc6c5c
    cursor pointer
.batchMove
  p
    color #303753
    font-size 12px
    margin 20px 0px 9px 0px
  .el-cascader
    width 100%
</style>
